package com.projectsquirrel;

import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Address;
import android.location.Geocoder;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class newObservation extends Activity implements LocationListener {
	

	private LocationManager myManager;
	private double latitude = 0;
	private double longitude = 0;
	private boolean gpsDisabled = false;
	private AlertDialog.Builder builder;
	AlertDialog gpsAlert;
	private TextView displayTime;
	private TextView displayDate;
	private TextView displayDate2;
	private TextView zipcodeEmg;
	private Observation newObs;
	private EditText zipCodeText;
	private int mHour = 01;
    private int mMinute = 01;
    private int mYear = 2000;
    private int mMonth = 01;
    private int mDay = 01;
    private Geocoder geocoder; 
    static final int TIME_DIALOG_ID = 999990099;
    static final int DATE_DIALOG_ID = 999990098;
    private int backCounter = 1;
    private String zipCode;
    private boolean showLayout1a;
    private FrameLayout layout1a;
    private FrameLayout layout1;
    private FrameLayout layout1p5;
    private FrameLayout layout2;
    private FrameLayout layout2p5;
    private FrameLayout layout3;
    private FrameLayout layout4;    
    private TableLayout confirmTable;    
    private Button nextObsButton1;
    private Button nextObsButton1p5;
    private Button nextObsButton2;
    private Button nextObsButton2p5;
    private Button nextObsButton3;
    private Button obsConfirmButton;
    private Button obsSubmitButton;
    private Button backObsButton1a;
    private Button q7yes;
    private Button q7no;
    private Button q7dk;
    
    private ScrollView scrollAll;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.observationform);
	    final String TAG = "Project_2_Group_6";
	    ImageButton infoIconButton = (ImageButton) findViewById(R.id.infoScreenIcon);
	    ImageButton settingsIconButton = (ImageButton) findViewById(R.id.settingsScreenIcon);
	     
	    layout1a = (FrameLayout) findViewById(R.id.frameLayout1a);
	    layout1 = (FrameLayout) findViewById(R.id.frameLayout1);
	    layout1p5 = (FrameLayout) findViewById(R.id.frameLayout1point5);
	    layout2 = (FrameLayout) findViewById(R.id.frameLayout2);
	    layout2p5 = (FrameLayout) findViewById(R.id.frameLayout2point5);
	    layout3 = (FrameLayout) findViewById(R.id.frameLayout3);
	    layout4 = (FrameLayout) findViewById(R.id.confirmationLayout);
	    confirmTable = (TableLayout) findViewById(R.id.confirmTable);
	    nextObsButton1 = (Button) findViewById(R.id.nextObsScreen1);
	    nextObsButton1p5 = (Button) findViewById(R.id.nextObsScreen1p5);	    
	    nextObsButton2 = (Button) findViewById(R.id.nextObsScreen2);
	    nextObsButton2p5 = (Button) findViewById(R.id.nextObsScreen2p5);
	    nextObsButton3 = (Button) findViewById(R.id.nextObsScreen3);
	    obsConfirmButton = (Button) findViewById(R.id.ObsConfirm);
	    obsSubmitButton = (Button) findViewById(R.id.ObsSubmit);
	    backObsButton1a = (Button) findViewById(R.id.backObsScreen1a);
	    scrollAll = (ScrollView) findViewById(R.id.ScrollAll);
	  
	    zipcodeEmg = (TextView) findViewById(R.id.zipcodeLabel);
	    zipCodeText = (EditText) findViewById(R.id.ZipCodeText);
	    zipCodeText.setVisibility(View.GONE);
	    zipcodeEmg.setVisibility(View.GONE);
	    //------Date and Time picker-------
	    Button mPickDate = (Button) findViewById(R.id.pickDate);
	    Button mPickTime = (Button) findViewById(R.id.pickTime); 
	    final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
	    //-------End date and Time picker-----
	    	    
	    final ToggleButton newLocationButton = (ToggleButton) findViewById(R.id.newLocButton);
	    final ToggleButton SubmittedBeforeButton = (ToggleButton) findViewById(R.id.sumbBeforeButton);
	    //final TextView finalResults = (TextView) findViewById(R.id.textView1d);
	    final TextView submittedBeforeText = (TextView) findViewById(R.id.textView1ac);
	    final TextView completitionStatus = (TextView) findViewById(R.id.textView2);
	    displayTime = (TextView) findViewById(R.id.timeDisplay);
	    displayDate = (TextView) findViewById(R.id.dateDisplay);
	    displayDate2 = (TextView) findViewById(R.id.dateDisplay2);
		final EditText generalComments = (EditText) findViewById(R.id.generalCommentText);
		final EditText treeComments = (EditText) findViewById(R.id.treeComments);
		final EditText feedComments = (EditText) findViewById(R.id.feedComments);

	    final Context context = getApplicationContext();
	    final SharedPreferences pref = getSharedPreferences("AppSettings",MODE_PRIVATE);
	    confirmTable.setColumnShrinkable(1, true);
	  	    
	    
	    //setup the gps manager
	    myManager = (LocationManager) getSystemService(LOCATION_SERVICE);	
	    geocoder = new Geocoder(getApplicationContext(), Locale.getDefault() );
        
	    
	    //final Observation newObs = new Observation(pref.getString("userEmail", null),idNumberObs);
	    newObs = new Observation(pref.getString("userEmail", null));
	    /*
		 * Please Note!
		 * This question only needs to be asked once and it will
		 * be entered into user Preferences, it is asking if 
		 * a user has submitted data for a different
		 * site before. If a user answers yes, this will
		 * become an auto-complete answer, if a user enters
		 * "NO" then it will re appear until a counter for the
		 * number times a user submits an obs
		 * while selecting "NO" on using them same site
		 * if the counter >= 2 this question will disappear.
		 * 
		 *   -Daniel
		 */
	    if(pref.getBoolean("SubmitDifSiteBefore", false)==true){
	    	SubmittedBeforeButton.setVisibility(View.GONE);
	    	submittedBeforeText.setVisibility(View.GONE);
		}
	    
	    final EditText numofGraySquirrelsEditText = (EditText) findViewById(R.id.numOfGrayEditText);
	    final EditText numofFoxSquirrelsEditText= (EditText) findViewById(R.id.numOfFoxEditText);
	
		numofGraySquirrelsEditText.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {
					if (numofGraySquirrelsEditText.getText() == null || numofGraySquirrelsEditText.getText().length() == 0)
						Toast.makeText(getApplicationContext(),"Please enter a value for Gray Squirrels",Toast.LENGTH_LONG).show();
					else
						newObs.setNumOfGray(numofGraySquirrelsEditText.getText().toString());
		    
			}
		    public void beforeTextChanged(CharSequence s, int start, int count,
		            int after) {
		        // TODO Auto-generated method stub
		 
		    }
		 
		    public void onTextChanged(CharSequence s, int start, int before,
		            int count) {
		        // TODO Auto-generated method stub
		 
		    }
		});
		numofFoxSquirrelsEditText.addTextChangedListener(new TextWatcher(){
			public void afterTextChanged(Editable s) {
				if (numofFoxSquirrelsEditText.getText() == null || numofFoxSquirrelsEditText.getText().length() == 0)
					Toast.makeText(getApplicationContext(),"Please enter a value for Fox Squirrels",Toast.LENGTH_LONG).show();
				else
					newObs.setNumOfGray(numofGraySquirrelsEditText.getText().toString());
	    
		}
		 
		    public void beforeTextChanged(CharSequence s, int start, int count,
		            int after) {
		        // TODO Auto-generated method stub
		 
		    }
		 
		    public void onTextChanged(CharSequence s, int start, int before,
		            int count) {
		        // TODO Auto-generated method stub
		 
		    }
		});
		completitionStatus.setText("10% complete");

		showLayout1a = pref.getBoolean("OverwriteDateTimeLoc", true);
		if(showLayout1a){
			layout1.setVisibility(View.GONE);
			nextObsButton2.setVisibility(View.GONE);
			layout1a.setVisibility(View.VISIBLE);
			nextObsButton1.setVisibility(View.VISIBLE);
			// display time and date for the user
		    displayTime.setText(newObs.getTime());
		    displayDate.setText(newObs.getDate());
		    displayDate2.setVisibility(View.GONE);
		    backCounter=0;
		    Log.i("backCounter", ""+backCounter);
		}
		else{
    		layout1.setVisibility(View.VISIBLE);
			nextObsButton1.setVisibility(View.GONE);
			nextObsButton1p5.setVisibility(View.VISIBLE);
			completitionStatus.setText("20% complete");
		    backCounter=1;
			//nextObsButton2.setVisibility(View.VISIBLE);
			displayDate2.setText(newObs.getDate());
		}

		
		final Spinner settingSpinner = (Spinner) findViewById(R.id.settingSpinner);
	    String[] settingsArr = {"Single-family home", "Apartment Building", "Highrise", "City Park", "Forest/Nature Preserve", 
	    		"Zoo/Arboretum/Botanical Garden", "Commercial Establishment", "School Campus", "Vacant Lot", "Cemetery", "Farmland"};
	    ArrayAdapter<String> settings = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, settingsArr );
	    settingSpinner.setAdapter(settings);
	    settingSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        newObs.setSetting(((String) parent.getItemAtPosition(pos)).toUpperCase());
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    }
		});
	    
	    // Create radio groups
	    
	    final RadioGroup nut_Tree_Group = (RadioGroup) findViewById(R.id.nut_Tree_Group);
	    final RadioGroup seed_Tree_Group = (RadioGroup) findViewById(R.id.seed_Tree_Group);
	    final RadioGroup fruit_Tree_Group = (RadioGroup) findViewById(R.id.fruit_Tree_Group);
	    final RadioGroup tiny_Tree_Group = (RadioGroup) findViewById(R.id.tiny_Tree_Group);
	    final RadioGroup cone_Tree_Group = (RadioGroup) findViewById(R.id.cone_Tree_Group);
	    final RadioGroup bird_Feed_Group = (RadioGroup) findViewById(R.id.bird_Feed_Group);
	    final RadioGroup human_Feed_Group = (RadioGroup) findViewById(R.id.human_Feed_Group);
	    final RadioGroup garbage_Feed_Group = (RadioGroup) findViewById(R.id.garbage_Feed_Group);
	    final RadioGroup other_Feed_Group = (RadioGroup) findViewById(R.id.other_Feed_Group);
	    final RadioGroup plant_Feed_Group = (RadioGroup) findViewById(R.id.plant_Feed_Group);
	    final RadioGroup num_Squirrels_Group = (RadioGroup) findViewById(R.id.num_Squirrels_Group);
	    final RadioGroup dog_Group = (RadioGroup) findViewById(R.id.dog_Group);
	    final RadioGroup cat_Group = (RadioGroup) findViewById(R.id.cat_Group);
	    final RadioGroup coyote_Group = (RadioGroup) findViewById(R.id.coyote_Group);
	    final RadioGroup hawk_Group = (RadioGroup) findViewById(R.id.hawk_Group);
	    final RadioGroup grain_Group = (RadioGroup) findViewById(R.id.grain_Group);

	    // Create radio group event listeners
	    nut_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	        	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	            newObs.setNutTree("" + t);
	        }
	    });
	    
	    seed_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	            newObs.setSeedTree("" + t);
	        }
	    });
	    
	    fruit_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setFruitTree("" + t);
	        }
	    });
	    
	    tiny_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setTinyTree("" + t);
	        }
	    });
	    
	    cone_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	            newObs.setConeTree("" + t);
	        }
	    });
	    
	    bird_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setBirdFeed("" + t);
	        }
	    });
	    
	    human_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
 	            newObs.setHumanFeed("" + t);
	        }
	    });
	    
	    garbage_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	            newObs.setGarbageFeed("" + t);
	        }
	    });
	    
	    plant_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setPlantFeed("" + t);
	        }
	    });
	    
	    other_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setOtherFeed("" + t);
	        }
	    });
	    num_Squirrels_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setNumOfSqurrelChange("" + t);
	        }
	    });
	    dog_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setDogs("" + t);
	        }
	    });
	    cat_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setCats("" + t);
	        }
	    });
	    coyote_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setCoyotes("" + t);
	        }
	    });
	    hawk_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setHawks("" + t);
	        }
	    });
	    grain_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	           	CharSequence s=rb.getText();
	        	String t=s.toString();
	        	t=t.toUpperCase();
	        	newObs.setPGrain("" + t);
	        }
	    });
	  
	    // Set radio button defaults
	    ((RadioButton) findViewById(R.id.nut_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.seed_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.fruit_Bearing_No)).performClick();
	    ((RadioButton) findViewById(R.id.tiny_Seeded_No)).performClick();
	    ((RadioButton) findViewById(R.id.coniferous_No)).performClick();
	    ((RadioButton) findViewById(R.id.bird_Feeders_Never)).performClick();
	    ((RadioButton) findViewById(R.id.human_Never)).performClick();
	    ((RadioButton) findViewById(R.id.garbage_Never)).performClick();
	    ((RadioButton) findViewById(R.id.trees_Never)).performClick();
	    ((RadioButton) findViewById(R.id.other_Never)).performClick();
	    ((RadioButton) findViewById(R.id.num_Squirrels_Same)).performClick();
	    ((RadioButton) findViewById(R.id.dogs_None)).performClick();
	    ((RadioButton) findViewById(R.id.cats_None)).performClick();
	    ((RadioButton) findViewById(R.id.hawks_Never)).performClick();
	    ((RadioButton) findViewById(R.id.coyotes_Never)).performClick();
	    ((RadioButton) findViewById(R.id.grains_Never)).performClick();



	    infoIconButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(newObservation.this, infoMenu.class);
		        startActivity(i);
			}	    	
	    });
	    
	    settingsIconButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(newObservation.this, settingsMenu.class);
		        startActivity(i);
			}	    	

	    });

	    
	    nextObsButton1.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		scrollAll.scrollTo(0,0);
	    		scrollAll.fling(-2000); 
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.VISIBLE);
	    		layout2.setVisibility(View.GONE);
	    		layout3.setVisibility(View.GONE);
	    		nextObsButton1.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.VISIBLE);
				//nextObsButton2.setVisibility(View.VISIBLE);
				nextObsButton3.setVisibility(View.GONE);
				obsSubmitButton.setVisibility(View.GONE);
				completitionStatus.setText("20% complete");
				backCounter++;
				//completitionStatus.setText("backCounter: " + backCounter);

			}
	    });
	    nextObsButton1p5.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				scrollAll.scrollTo(0,0);
				scrollAll.fling(-2000); 
				layout1a.setVisibility(View.GONE);
				layout1.setVisibility(View.GONE);
				layout1p5.setVisibility(View.VISIBLE);
				//layout2.setVisibility(View.VISIBLE);
				layout3.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.GONE);
				//nextObsButton2.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.VISIBLE);				
				//nextObsButton3.setVisibility(View.VISIBLE);				
				
				if(newLocationButton.isChecked()){
					newObs.setUsingSameSite("YES");
				}
				else{
					newObs.setUsingSameSite("NO");
				}
				/*
				 * Please Note!
				 * This question only needs to be asked once and it will
				 * be entered into user Preferences, it is asking if 
				 * a user has submitted data for a different
				 * site before. If a user answers yes, this will
				 * become an auto-complete answer, if a user enters
				 * "NO" then it will re appear until a counter for the
				 * number times a user submits an obs
				 * while selecting "NO" on using them same site
				 * if the counter >= 2 this question will disappear.
				 * 
				 *   -Daniel
				 */
				if(gpsDisabled){
					zipCode = zipCodeText.getText().toString();
					String regTest="([0-9][0-9][0-9][0-9][0-9])";
					Pattern p = Pattern.compile(regTest,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
				    Matcher m = p.matcher(zipCode);
				    if (!m.find()||zipCode.length()!=5)
				    {
				    	Toast.makeText(getApplicationContext(),"Please enter a valid Zipcode in the form of #####",Toast.LENGTH_LONG).show();
				    }
				    else{				    	
				    	newObs.setZip(zipCode);
				    }
				}
				if(SubmittedBeforeButton.isChecked()){
					newObs.setUsingDifSite("YES");
				}
				else{
					newObs.setUsingDifSite("NO");
				}
				newObs.setGeneralComments(generalComments.getText().toString());
				completitionStatus.setText("40% complete");
				backCounter++;
				//completitionStatus.setText("backCounter: " + backCounter);

			}
			
	    });
	    nextObsButton2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				scrollAll.scrollTo(0,0);
				scrollAll.fling(-2000); 
				layout1a.setVisibility(View.GONE);
				layout1.setVisibility(View.GONE);
				layout1p5.setVisibility(View.GONE);
				layout2.setVisibility(View.VISIBLE);
				layout3.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.VISIBLE);				
				//nextObsButton3.setVisibility(View.VISIBLE);				
				
				completitionStatus.setText("60% complete");
				backCounter++;
				//completitionStatus.setText("backCounter: " + backCounter);
			}
			
	    });
	    
	    nextObsButton2p5.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				scrollAll.scrollTo(0,0);
				scrollAll.fling(-2000); 
				layout1a.setVisibility(View.GONE);
				layout1.setVisibility(View.GONE);
				layout1p5.setVisibility(View.GONE);
				layout2.setVisibility(View.GONE);
				layout2p5.setVisibility(View.VISIBLE);
				layout3.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.GONE);				
				nextObsButton3.setVisibility(View.VISIBLE);				
				newObs.setTreeComments(treeComments.getText().toString());
				completitionStatus.setText("80% complete");
				backCounter++;
				//completitionStatus.setText("backCounter: " + backCounter);
			}
			
	    });
	   
	    nextObsButton3.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		scrollAll.scrollTo(0,0);
	    		scrollAll.fling(-2000); 
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
				layout2.setVisibility(View.GONE);
				layout2p5.setVisibility(View.GONE);
				layout3.setVisibility(View.VISIBLE);
				nextObsButton1.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.GONE);

				nextObsButton3.setVisibility(View.GONE);
				obsConfirmButton.setVisibility(View.VISIBLE);
				backCounter++;
				newObs.setFeedComments(feedComments.getText().toString());
				//completitionStatus.setText("backCounter: " + backCounter);
				completitionStatus.setText("99% complete");

			}
	    });
	    
	    
	    
	    	    
	    obsConfirmButton.setOnClickListener(new OnClickListener() {
	    	public void onClick(View v) {
	    		scrollAll.scrollTo(0,0);
	    		scrollAll.fling(-2000);  
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout3.setVisibility(View.GONE);
	    		layout4.setVisibility(View.VISIBLE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.GONE);
				obsConfirmButton.setVisibility(View.GONE);
				obsSubmitButton.setVisibility(View.VISIBLE);
				
				
				SharedPreferences.Editor editor = pref.edit();
				
				//pass what we got at the end of the survey
				newObs.setLatLong(latitude, longitude);
				newObs.setZip(zipCode);
				
				/*
				 * Please Note!
				 * This question only needs to be asked once and it will
				 * be entered into user Preferences, it is asking if 
				 * a user has submitted data for a different
				 * site before. If a user answers yes, this will
				 * become an auto-complete answer, if a user enters
				 * "NO" then it will re appear until a counter for the
				 * number times a user submits an obs
				 * while selecting "NO" on using them same site
				 * if the counter >= 2 this question will disappear.
				 * 
				 *   -Daniel
				 */				
				int diffSiteCount = 0;
				if(pref.getBoolean("SubmitDifSiteBefore", false)==true){
					newObs.setUsingDifSite("YES");
				}
				else{
					//it must be false
					if(newObs.getUsingSameSite().equals("NO")){
						diffSiteCount = pref.getInt("DifSiteCounter", 0);								
						editor.putInt("DifSiteCounter", diffSiteCount+1);
						editor.commit();
						int temp = pref.getInt("DifSiteCounter", 0);
						if(temp>=2){
							Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
							editor.putBoolean("SubmitDifSiteBefore", true);
							editor.commit();
						}
					}
					else{
						//yes, using the same site						
						int temp = pref.getInt("DifSiteCounter", 0);
						if(temp>=2){
							Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
							editor.putBoolean("SubmitDifSiteBefore", true);
							editor.commit();
						}
					}
				}		   
				//finalResults.setText(newObs.toString());
				((TextView) findViewById(R.id.confirmTime)).setText(newObs.getHour() + ":" 
						+ newObs.getMinute() + " " + newObs.getAMPM());
				((TextView) findViewById(R.id.confirmBird)).setText(newObs.getFeedFromBirdFeeder());
				((TextView) findViewById(R.id.confirmCone)).setText(newObs.getConTrees());
				((TextView) findViewById(R.id.confirmDate)).setText(newObs.getMonth() + "/" 
						+ newObs.getDay() + "/" + newObs.getYear());
				((TextView) findViewById(R.id.confirmEmail)).setText(newObs.getEmail());
				if(newObs.getFeedFromComments().trim().length() != 0)
					((TextView) findViewById(R.id.confirmFeedComments)).setText(newObs.getFeedFromComments());
				((TextView) findViewById(R.id.confirmFruit)).setText(newObs.getFruitTrees());
				((TextView) findViewById(R.id.confirmGarbage)).setText(newObs.getFeedFromGarbage());
				((TextView) findViewById(R.id.confirmHandouts)).setText(newObs.getFeedFromHandouts());
				((TextView) findViewById(R.id.confirmLatitude)).setText("" + newObs.getLatitude());
				((TextView) findViewById(R.id.confirmLongitude)).setText(newObs.getLongitude() + "");
				((TextView) findViewById(R.id.confirmNumFox)).setText(newObs.getNumOfFoxSquirrels());
				((TextView) findViewById(R.id.confirmNumGray)).setText(newObs.getNumOfGraySquirrels());
				((TextView) findViewById(R.id.confirmNumSquirrelChange)).setText(newObs.getNumOfSqurChange());
				((TextView) findViewById(R.id.confirmNut)).setText(newObs.getNutTrees());
				((TextView) findViewById(R.id.confirmOtherFeed)).setText(newObs.getFeedFromOther());
				if(newObs.getOtherTreeComments().trim().length() != 0)
					((TextView) findViewById(R.id.confirmOtherTree)).setText(newObs.getOtherTreeComments());
				((TextView) findViewById(R.id.confirmPlants)).setText(newObs.getFeedFromTrees());
				((TextView) findViewById(R.id.confirmSeed)).setText(newObs.getSeedTrees());
				((TextView) findViewById(R.id.confirmSetting)).setText(newObs.getSetting());
				((TextView) findViewById(R.id.confirmTiny)).setText(newObs.getTinyTrees());
				((TextView) findViewById(R.id.confirmZIP)).setText(newObs.getZIP());
				((TextView) findViewById(R.id.confirmCats)).setText(newObs.getNumOfSiteCats());
				((TextView) findViewById(R.id.confirmCoyotes)).setText(newObs.getNumOfSiteCoyotes());
				((TextView) findViewById(R.id.confirmDogs)).setText(newObs.getNumOfSiteDogs());
				if(newObs.getGeneralComments().trim().length() != 0)
					((TextView) findViewById(R.id.confirmGeneralComments)).setText(newObs.getGeneralComments());
				((TextView) findViewById(R.id.confirmHawks)).setText(newObs.getNumOfSiteHawks());
				((TextView) findViewById(R.id.confirmPGrain)).setText(newObs.getNumOfSitePGrain());
				((TextView) findViewById(R.id.confirmSameSite)).setText(newObs.getUsingSameSite());
				((TextView) findViewById(R.id.confirmDiffSite)).setText(newObs.getUsedDifferentSite());

				
				completitionStatus.setText("Almost done! Just press Submit!");

				backCounter++;
			}
	    });
	    
	    obsSubmitButton.setOnClickListener(new OnClickListener()
	    {
	    	public void onClick(View v)
	    	{
	    		layout4.setVisibility(View.GONE);
	    		String fName = newObs.getName();
				try{
					OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fName, 0));
					out.write(newObs.toString());
					Log.i(TAG, newObs.toString());
					out.close();
				}
				catch(Throwable t) {
					Toast.makeText(context, "Exception: "+ t.toString(), 5000).show();
				}
				Toast.makeText(getApplicationContext(),"Observation Submitted!",Toast.LENGTH_LONG).show();
				backCounter = 1;
				finish();
	    	}
	    });
	    
	    
	    	 // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
        		//Toast.makeText(getApplicationContext(), "PickDate!", 5000).show();
            }
        });
	  
        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
        		//Toast.makeText(getApplicationContext(), "PickTime!", 5000).show();
            }
        });
	    

	
     }
     	@Override
	protected void onStart(){
     	// for the dialog indicating the gps is disabled
    	builder = new AlertDialog.Builder(this);
		builder.setMessage("Your GPS service is disabled, You will have to enter the f" +
	    		"ull zip code manually. Sorry for this inconvience. If you do not know the zip code " +
	    		"please feel free to click on the info button for help.")
	           .setCancelable(false)
	           .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    
	               }
	     });

		super.onStart();
	}
	@Override
	protected void onDestroy() {
		stopListening();
		super.onDestroy();
	}
	
	@Override
	protected void onPause() {
		stopListening();
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		startListening();
		super.onResume();
	}
	
    // updates the date in the TextView
    private void updateDisplayDate() {
    	newObs.setDate(mDay, mMonth, mYear);
    	displayDate.setText(newObs.getDate());

    }
    
    
    private void updateDisplayTime() {
    	newObs.setTime(mHour, mMinute);
    	displayTime.setText(newObs.getTime());               
    }
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mHour, mMinute, false);
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case TIME_DIALOG_ID:
                ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
                break;
            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
                break;
        }
    }  
    
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    	public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplayDate();
            }
    };

    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplayTime();
            }
        };

	//GPS required methods---
	private void startListening() {
		myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
		//myManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
	}

	private void stopListening() {
		if (myManager != null)
			myManager.removeUpdates(this);
	}
	public void onLocationChanged(Location location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		try{
	        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
	        zipCode = addresses.get(0).getPostalCode();
	        zipCode.concat("-0000");
	        //tvLocationText.setText(zipCode);
	        }
	        catch(Exception e){
	        	//tvLocationText.setText(e.toString());
	        	Log.e("Geocoder Error:", e.toString());
	        }
		
	}
	public void onProviderDisabled(String provider) {
		gpsDisabled = true;
		gpsAlert = builder.create();
		gpsAlert.show();
		zipCodeText.setVisibility(View.VISIBLE);
	    zipcodeEmg.setVisibility(View.VISIBLE);
	}

	public void onProviderEnabled(String provider) {
		gpsDisabled = false;
		zipCodeText.setVisibility(View.GONE);
	    zipcodeEmg.setVisibility(View.GONE);
	}

	public void onStatusChanged(String provider, int status, Bundle extras) {}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
	        switch(backCounter){
	        case 0:	        	 
	        	finish();	        		
	        	break;
	        case 1:	        	
	        	if(showLayout1a){
	        		scrollAll.scrollTo(0,0);
	        		scrollAll.fling(-2000); 
	        		layout1a.setVisibility(View.VISIBLE);
	        		layout1.setVisibility(View.GONE);
	        		layout1p5.setVisibility(View.GONE);
	        		layout2.setVisibility(View.GONE);
			    	layout3.setVisibility(View.GONE);
			    	nextObsButton1.setVisibility(View.VISIBLE);
			    	nextObsButton1p5.setVisibility(View.GONE);
			    	nextObsButton2.setVisibility(View.GONE);
			    	nextObsButton3.setVisibility(View.GONE);
			    	obsSubmitButton.setVisibility(View.GONE);
	    			// display time and date for the user
	    		    displayTime.setText(newObs.getTime());
	    		    displayDate.setText(newObs.getDate());
	    		    displayDate2.setVisibility(View.GONE);
	    		    backCounter--;
					((TextView) findViewById(R.id.textView2)).setText("10% complete");
	        	}
	        	else finish();
        		
	        	break;
	        case 2:
	        	scrollAll.scrollTo(0,0);
	        	scrollAll.fling(-2000); 
	        	layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.VISIBLE);
        		layout1p5.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout2p5.setVisibility(View.GONE);

	    		layout3.setVisibility(View.GONE);
		    	nextObsButton1p5.setVisibility(View.VISIBLE);

				nextObsButton2.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.GONE);

				nextObsButton3.setVisibility(View.GONE);
				obsSubmitButton.setVisibility(View.GONE);
				backCounter--;
				((TextView) findViewById(R.id.textView2)).setText("20% complete");

				break;
	        case 3:
	        	scrollAll.scrollTo(0,0);
	        	scrollAll.fling(-2000); 
	        	layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout1p5.setVisibility(View.VISIBLE);
	    		layout2.setVisibility(View.GONE);
	    		layout2p5.setVisibility(View.GONE);

	    		layout3.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.GONE);

				nextObsButton2.setVisibility(View.VISIBLE);
				nextObsButton3.setVisibility(View.GONE);		
				obsConfirmButton.setVisibility(View.GONE);
				obsSubmitButton.setVisibility(View.GONE);
				backCounter--;
				((TextView) findViewById(R.id.textView2)).setText("40% complete");

	        	break;
	        case 4:
	        	scrollAll.scrollTo(0,0);
	        	scrollAll.fling(-2000); 
	        	layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout1p5.setVisibility(View.GONE);
	    		layout2p5.setVisibility(View.GONE);

	    		layout2.setVisibility(View.VISIBLE);
	    		layout3.setVisibility(View.GONE);
				nextObsButton1.setVisibility(View.GONE);
				nextObsButton1p5.setVisibility(View.GONE);

				nextObsButton2.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.VISIBLE);

				nextObsButton3.setVisibility(View.GONE);		
				obsConfirmButton.setVisibility(View.GONE);
				obsSubmitButton.setVisibility(View.GONE);
				backCounter--;
				((TextView) findViewById(R.id.textView2)).setText("60% complete");
				break;
	        case 5:
	        	scrollAll.scrollTo(0,0);
	        	scrollAll.fling(-2000); 
	        	layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout2p5.setVisibility(View.VISIBLE);

	    		layout3.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton2p5.setVisibility(View.GONE);

				nextObsButton3.setVisibility(View.VISIBLE);		
				obsConfirmButton.setVisibility(View.GONE);
				obsSubmitButton.setVisibility(View.GONE);
				backCounter--;
				((TextView) findViewById(R.id.textView2)).setText("80% complete");
	        	break;
	        case 6:
	        	scrollAll.scrollTo(0,0);
	        	scrollAll.fling(-2000); 
	        	layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout4.setVisibility(View.GONE);
	    		layout3.setVisibility(View.VISIBLE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.GONE);
				obsConfirmButton.setVisibility(View.VISIBLE);
				obsSubmitButton.setVisibility(View.GONE);
				backCounter--;
				((TextView) findViewById(R.id.textView2)).setText("99% complete");
	        	break;
	        case 7:
	        	scrollAll.scrollTo(0,0);
	        	scrollAll.fling(-2000); 
	        	layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout4.setVisibility(View.GONE);
	    		layout3.setVisibility(View.VISIBLE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.GONE);
				obsConfirmButton.setVisibility(View.VISIBLE);
				obsSubmitButton.setVisibility(View.GONE);
				backCounter--;
				((TextView) findViewById(R.id.textView2)).setText("99% complete");
	        	break;
	        default:        	
	        	finish();
	        	break;
	        }
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
	
	    
}
